<template>
  <el-dialog
    v-el-drag-dialog
    :title="!dataForm.id ? '新增模板' : '修改模板'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="模板名称:" prop="name" label-width="100px">
        <el-input type="text" placeholder="内容限制20字以内" v-model.trim="dataForm.name" maxlength="20" show-word-limit style="width:400px"/>
      </el-form-item>
      <el-form-item label="活动时间:" prop="time">
        <el-date-picker
          :editable="false"
          v-model="dataForm.time"
          type="daterange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="-"
          start-placeholder="活动开始时间"
          end-placeholder="活动结束时间"/>
      </el-form-item>
      <el-form-item label="模板排序:" prop="sort" label-width="100px">
        <el-input type="number" v-model.trim="dataForm.sort" placeholder="限制数字" style="width:120px"/>
      </el-form-item>
      <el-form-item label="备注： " prop="remark" label-width="100px">
        <el-input type="textarea" :rows="6" placeholder="备注" v-model="dataForm.remark" style="width:400px" />
      </el-form-item>
      <el-form-item label="图标" prop="imageUrl">
        <el-upload
          :class="{hide:hideUpload}"
          :action="this.$http.adornUrl(`/sign/uploadTurntable?path=${this.dataForm.prizePath}&token=${this.$cookie.get('token')}`)"
          :limit="1"
          list-type="picture-card"
          :file-list="dataForm.img"
          :before-upload="beforeAvatarUpload"
          :on-preview="handlePreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :on-exceed="onExceed"
          style="margin-left: 20px; width: 200px; height: 150px">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
          <img width="100%" height="100px" :src="dataForm.imageUrl" alt="">
        </el-dialog>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
  export default {
    data () {
      return {
        dialogVisible: false,
        hideUpload: false,
        visible: false,
        dataForm: {
          prizePath: 'prize',
          id: '',
          name: '',
          img: [],
          imageUrl: '',
          remark: '',
          sort: '',
          time: []
        },
        dataRule: {
          name: [
            { required: true, message: '活动名称不能为空', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '类别排序不能为空', trigger: 'blur' },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '类别排序为正整数', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/gif'
        if (!isJPG) {
          this.$message.error('上传图片只能是  JPG,PNG,GIF 格式！')
        }
      },
      // 图片预览
      handlePreview (file) {
        debugger
        console.log(file.url)
        this.dataForm.imageUrl = file.url
        this.dialogVisible = true
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        this.hideUpload = fileList.length >= 1
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.img.push({name: 'prize', url: res.data})
        }
        console.log(this.dataForm.img)
        debugger
      },
      // 删除文件之前的钩子函数
      handleRemove (file, fileList) {
        this.hideUpload = fileList.length >= 1
        for (var i = 0; i < this.dataForm.img.length; i++) {
          var picc = this.dataForm.img[i]
          if (picc.url === file.url) {
            this.dataForm.img.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 6000
        })
      },
      init (id) {
        debugger
        this.visible = true
        this.hideUpload = false
        this.dataForm.id = id || 0
        this.$nextTick(() => {
          this.dataForm.img = []
          this.dataForm.time = []
          this.$refs['dataForm'].resetFields()
          debugger
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sign/getTurntableById/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.id = data.data.id
                this.dataForm.name = data.data.name
                this.dataForm.remark = data.data.remark
                this.dataForm.sort = data.data.sort
                this.dataForm.time = [data.data.beginTime, data.data.endTime]
                if (data.data.imageUrl != null && data.data.imageUrl !== '') {
                  this.dataForm.img.push({name: 'prize', url: 'http://image.yilianbaihui.cn/consumer/' + data.data.imageUrl})
                  this.hideUpload = true
                }
              }
            })
          }
        })
      },
      dataFormSubmit () {
        debugger
        console.log(this.dataForm.id)
        if (this.dataForm.img.length > 0) {
          let index = this.dataForm.img[0].url.toString().lastIndexOf('\/')
          this.dataForm.imageUrl = this.dataForm.img[0].url.toString().substring(index + 1, this.dataForm.img[0].url.toString().length)
          this.dataForm.imageUrl = this.dataForm.prizePath + '/' + this.dataForm.imageUrl
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sign/${!this.dataForm.id ? 'addTurntable' : 'modifyTurntableById'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': parseInt(this.dataForm.id) || undefined,
                'name': this.dataForm.name,
                'beginTime': this.dataForm.time[0],
                'endTime': this.dataForm.time[1],
                'sort': this.dataForm.sort,
                'remark': this.dataForm.remark,
                'imageUrl': this.dataForm.imageUrl
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
<style>
  .hide .el-upload--picture-card {  display: none; }
</style>
